package org.tao.lightningmq.nameserver;

import io.netty.util.internal.StringUtil;
import org.tao.lightningmq.nameserver.common.CommonCache;
import org.tao.lightningmq.nameserver.core.InValidServiceRemoveTask;
import org.tao.lightningmq.nameserver.core.NameServerNettyStarter;
import org.tao.lightningmq.nameserver.enums.ReplicationModeEnum;
import org.tao.lightningmq.nameserver.enums.ReplicationRoleEnum;
import org.tao.lightningmq.nameserver.replication.*;

import java.io.IOException;

/**
 * NameServer 启动类
 */
public class NameServerStartUp {

    private static NameServerNettyStarter nameServerNettyStarter;
    private static ReplicationService replicationService = new ReplicationService();

    private static void initInvalidServerRemoveTask() {
        Thread inValidServiceRemoveTask = new Thread(new InValidServiceRemoveTask());
        inValidServiceRemoveTask.setName("invalid-server-remove-task");
        inValidServiceRemoveTask.start();
    }

    private static void initReplication() {
        ReplicationModeEnum replicationMode = replicationService.checkProperties();
        CommonCache.setReplicationMode(replicationMode);
        if (replicationMode == null) return;
        replicationService.startReplicationTask(replicationMode);
        BaseReplicationTask replicationTask = null;
        switch (replicationMode) {
            case MASTER_SLAVE:
                ReplicationRoleEnum roleEnum = ReplicationRoleEnum.getEnumByCode(
                        CommonCache.getNameserverProperties().getMasterSlaveReplicationProperties().getRole());
                if (ReplicationRoleEnum.MASTER.equals(roleEnum)) {
                    replicationTask = new MasterReplicationMsgSendTask("master-replication-msg-send-task");
                } else if (ReplicationRoleEnum.SLAVE.equals(roleEnum)) {
                    replicationTask = new SlaveReplicationHeartBeatTask("slave-replication-heart-beat-send-task");
                }
                break;
            case TRACE:
                if (!StringUtil.isNullOrEmpty(CommonCache.getNameserverProperties().getTraceReplicationProperties().getNextNode())) {
                    replicationTask = new NodeReplicationSendMsgTask("node-replication-msg-send-task");
                } else return;
                break;
            default:
                throw new IllegalArgumentException("未知的复制模式");
        }
        replicationTask.startTaskAsync();
        CommonCache.setReplicationTask(replicationTask);
    }

    public static void main(String[] args) throws IOException {
        CommonCache.getPropertiesLoader().loadProperties();
        initInvalidServerRemoveTask();
        initReplication();
        nameServerNettyStarter = new NameServerNettyStarter(CommonCache.getNameserverProperties().getNameserverPort());
        nameServerNettyStarter.startServer();
    }
}
